var orm = require('orm');

var express_orm = orm.express(require("./config/mysql_config.js"), {
    define: function(db, models) {
        for (var tablename in tables) {
            (function(tablename) {
                var table_info = tables[tablename];
                var id;
                for (var key in table_info) {
                    if (!id) {
                        key.indexOf("_id") !== -1 && key.split("-").length === 2;
                        id = key;
                    }
                    table_info[key] = typeMap[table_info[key]];
                }
                console.log("ORM定义初始化定义表：", tablename, "\t\t主键：", id);
                models[tablename] = db.define(tablename, table_info, {
                    id: id
                });
            }(tablename));
        }
    }
});

/*
 *  数据库表映射信息
 */
var typeMap = {
    "tinyint": Boolean,
    "int": Number,
    "float": Number,
    "double": Number,
    "varchar": String,
    "text": String,
    "char": String,
    "boolean": Boolean,
}


var tables = {
    "userslist": {
        'id': "int",
        "username": "varchar",
        "pwd": "varchar",
        "roletype": "char"
    },
    "news": {
        "newsid": "int",
        "newstitle": "varchar",
        "uptime": "varchar",
        "author": "varchar",
        "newstext": "varchar",
        "type": "int"
    },
    "case": {
        "id": "int",
        "uptime": "varchar",
        "title": "varchar",
        "imgurl": "varchar",
        "url": "varchar",
        "type": "int"
    },
    "message": {
        "msgid": "int",
        "nickname": "varchar",
        "msgtitle": "varchar",
        "uptime": "varchar",
        "msgtext": "varchar",
        "email": "varchar",
        "type": "int"
    },
    "reply": {
        "replyid": "int",
        "msgid": "int",
        "replytitle": "varchar",
        "replytext": "varchar",
    }
};

module.exports = express_orm;